<?php
App::import('Controller','Assets.CmsAssets');
class ListingAssetsController extends CmsAssetsController
{
	var $name = 'ListingAssets';
	var $components =array('Auth','Session','RequestHandler');
	function beforeFilter()
	{
		parent::beforeFilter();
		$this->Auth->allow('index','add','all');
		$this->indexMethods = cr('indexMethods.ListingAsset');
	}
	
	function delete($id)
	{
		$allowDelete = false;
		$listingId = $this->ListingAsset->field('listing_id',array("id"=>$id));
		if($id && AppUtility::allowPaidListing())
		{
			$ownerId = $this->ListingAsset->Listing->field("owner_id",array("id"=>$listingId));
			if($ownerId && $this->Session->read("Auth.User.id") == $ownerId)
			{
				$allowDelete = true;
			}		
		}
		if($id && $allowDelete == false && cr("ListingConfig.allow_asset_edit"))
		{
			$userId = $this->ListingAsset->field('user_id',array("id"=>$id));
			if($userId && $userId == $this->Session->read("Auth.User.id"))
			{
				$allowDelete = true;
			}
		}
		if($allowDelete)
		{
			$this->ListingAsset->delete($id);
			$this->ListingAsset->Listing->clearRecordCache($listingId,true);
			if(!$this->RequestHandler->isAjax())
			{
				$this->successMsg(__("Image has been deleted"));
				$url = $this->referer(array("action"=>"index","my"));
				$this->redirect($url);
			}else
			{
				$this->_stop();
			}
		}
		$this->redirect("/");
	}
	function admin_delete($id = null)
	{
		$listingId = $this->ListingAsset->field('listing_id',array('ListingAsset.id'=>$id));
		$this->ListingAsset->Listing->clearRecordCache($listingId,true);
		
		$this->ListingAsset->id = $id;
		if($this->ListingAsset->del($id))
		{
			$this->successMsg(__('Image has been deleted.!'));
		}else
		{
			$this->errorMsg(__('Sorry, image could not be deleted.!'));	
		}
		$this->redirect($this->referer());		
	}
	function add($id = null)
	{
		$listing = $this->ListingAsset->Listing->find('first',array('conditions'=>array('id'=>$id),'recursive'=>-1));
		$authedUser = $this->Session->read('Auth.User');
		if(empty($authedUser) && cr('ListingConfig.guest_upload_photo') != 1)
		{
			$this->Session->write('Auth.redirect','/'.$this->params['url']['url']);
			$this->redirect('/users/login');
		}
		
		if(!$listing)
		{
			$this->redirect('/');
		}
		if(AppUtility::allowPaidListing())
		{
			$EffectivePlan = cri("PaidListings.ListingPlan")->getEffectivePlan($listing['Listing']['id']);
			if($EffectivePlan->limitImages())
			{
				$addedCount = $this->ListingAsset->find("count",array("recursive"=>-1,'conditions'=>array("listing_id"=>$listing['Listing']['id'])));
				$allowedCount = $EffectivePlan->getAllowedTotalImagesCount();
				if(($addedCount >= $allowedCount) || ($EffectivePlan->allowGallery() == false && (!$this->Session->read("Auth.User.id") || $this->Session->read("Auth.User.id") != $listing['Listing']['owner_id'])) )
				{
					$this->errorMsg(__("You don't have permission to upload image."));
					$this->redirect($this->referer($listing['Listing']['viewUrl']));
				}
			}
		}
		$this->set('listing',$listing);
		if($this->data && $this->data['ListingAsset']['name']['name'] == '')
		{
			$this->__afterAssetFail($this->data,null);
			$this->redirect($this->referer());
		}else
		{
			parent::add('Listing',$id);
		}		
	}
	
	function __afterAssetAdd($uploadedData,$itemInfo)
	{
		if(!$this->ListingAsset->Listing->hasDefaultImage($itemInfo['Listing']['id']))
		{
			if($this->ListingAsset->id)
			{
				$this->ListingAsset->makeAsDefault($itemInfo['Listing']['id'],$this->ListingAsset->id);
			}
		}
		$this->ListingAsset->Listing->clearRecordCache($itemInfo['Listing']['id'],true);
		$this->successMsg(__('The image has been uploaded successfully', true));
		$this->redirect(array('controller'=>'listings','action'=>'view',$itemInfo['Listing']['slug']));			
	}
	
	function __afterAssetFail($uploadedData,$itemInfo)
	{
		$this->errorMsg(__('The image could not be saved. Please, try again.', true));
	}
	
	function view($id = null)
	{
		$isAdmin = false;
		if(isset($this->params['admin']))
		{
			$isAdmin = true;	
		}
		$this->ListingAsset->recursive = 0;
		if($isAdmin)
		{
			$assetData = $this->ListingAsset->findById($id);
			$neighborCondition = array('listing_id'=>$assetData['ListingAsset']['listing_id']);
		}else
		{
			$assetData = $this->ListingAsset->findByIdAndStatus($id,ListingAsset::PUBLISHED);
			$neighborCondition = array('listing_id'=>$assetData['ListingAsset']['listing_id'],'status'=>ListingAsset::PUBLISHED);
		}
		if(empty($assetData))
		{
			$this->errorMsg(__('Invalid URL'));
			$this->redirect($this->referer());
		}
		$this->helpers[] = 'Comments.Comment';
		
		$neighbors = $this->ListingAsset->find('neighbors',array('conditions'=>$neighborCondition,'recursive'=>-1,'fields'=>array('id'),'callbacks'=>false));
		$listing = $this->ListingAsset->Listing->find('first',array('conditions'=>array('Listing.id'=>$assetData['ListingAsset']['listing_id']),'recursive'=>-1));
		
		$this->set(compact('assetData','neighbors'));
		$this->set('listing',array('Listing'=>$assetData['Listing']));
		$this->pageTitle = sprintf(__('%s\'s Gallery'),$assetData['Listing']['title']);
		//$this->helpers[] = 	"Reports.Report";
	}	
	
	function admin_view($listingId = null)
	{
		$this->view($listingId);
		$this->render("view");
	}
	
	function admin_setAsDefault($id = null)
	{
		$this->ListingAsset->recursive = -1;
		$listingAsset = $this->ListingAsset->findByid($id);
		if(empty($listingAsset))
		{
			$this->errrorMsg(__('Invalid URL'));
			$this->redirect($this->referer());
		}
		$this->ListingAsset->id = $id;
		if($listingAsset["ListingAsset"]["status"] == ListingAsset::UNPUBLISHED)
		{
			$this->ListingAsset->saveField('status',ListingAsset::PUBLISHED);
		}
		$this->ListingAsset->updateAll(array('is_default'=>0),array('ListingAsset.listing_id'=>$listingAsset["ListingAsset"]["listing_id"]));
		$setAsDefaultResponse = $this->ListingAsset->saveField('is_default',1);
		if($setAsDefaultResponse)
		{
			$this->successMsg(__("Default image has been changed."));
		}else
		{
			$this->errorMsg(__("Default image has been changed."));
		}
		$this->ListingAsset->Listing->clearRecordCache($listingAsset['ListingAsset']['listing_id'],true);
		$this->redirect($this->referer());
	}
	
	function admin_changeStatus($id = null)
	{
		$this->ListingAsset->recursive = -1;
		$listingAsset = $this->ListingAsset->findByid($id);
		if(empty($listingAsset))
		{
			$this->errrorMsg(__('Invalid URL'));
			$this->redirect($this->referer());
		}
		$this->ListingAsset->id = $id;
		if($listingAsset["ListingAsset"]["status"] == ListingAsset::UNPUBLISHED)
		{
			$statusToSave = ListingAsset::PUBLISHED;
			$successMsg = 'Image has been published.';
			$errorMsg = 'Sorry,image could not be published.';
		}else
		{
			$statusToSave = ListingAsset::UNPUBLISHED;
			$successMsg = 'Image has been unpublished.';
			$errorMsg = 'Sorry,image could not be unpublished.';
		}
		if($this->ListingAsset->saveField('status',$statusToSave))
		{
			$this->successMsg(__($successMsg));
			$this->ListingAsset->Listing->clearRecordCache($listingAsset['ListingAsset']['listing_id'],true);
		}else
		{
			$this->errorMsg(__($errorMsg));			
		}	
		$this->redirect($this->referer());
	}
	
	
	
	function index($type = false)
	{
		$this->paginate['order'] = array('ListingAsset.created DESC');
		$this->paginate['recursive'] = 0;
		if(isset($this->params['named']['limit']))
		{
			unset($this->params['named']['limit']);
			unset($this->passedArgs['limit']);
		}
		$this->paginate['limit'] = 150;
		$this->paginate['contain'] = array("Listing");
		$this->paginate['conditions']['ListingAsset.status'] = ListingAsset::PUBLISHED; 
		$assetToShow = null;
		if(isset($this->params['named']['show']))
		{
			$assetToShow = $this->params['named']['show'];
			unset($this->params['named']['show']);
			unset($this->passedArgs['show']);
		}
		$this->set("assetToShow",$assetToShow);
		if($type)
		{
			if(in_array($type, array_keys($this->indexMethods)))
			{
				$subMethodName = $this->indexMethods[$type]['method'];
				if(isset($this->indexMethods[$type]['title']))
				{
					$this->pageTitle = __($this->indexMethods[$type]['title']);
				}
				$this->{$subMethodName}();
				$listingAssets = $this->paginate();
				$this->set(compact('listingAssets'));
			}
			else
			{
				$this->errorMsg(__("Invalid URL"));
				$this->redirect("/");
			}
		}else
		{
			$this->errorMsg(__("Invalid Type"));
			$this->redirect("/");
		}	
		
	}
	
	function __listingGallery()
	{	
		if(!isset($this->params['named']['listingId']) || !isset($this->params['pass']['0']))
		{
			$this->__invalidUrl('Invalid parameter.');
		}
		$listingId = 	$this->params['named']['listingId'];
		$order = "created ASC";
        $userId = @$this->params['named']['userId'];
        //Show User asset once. 
        unset($this->params['named']['userId']);
        $imageLimit = null;
		if(AppUtility::allowPaidListing())
		{
			$EffectivePlan = cri("PaidListings.ListingPlan")->getEffectivePlan($listingId);
			if($EffectivePlan->limitImages() == true)
			{
				$imageLimit = $EffectivePlan->getAllowedTotalImagesCount();
			}
		}
		$this->paginate['conditions']['ListingAsset.listing_id'] =  $listingId;
		if($imageLimit > 0)
		{
			$imageIds = $this->ListingAsset->find("list",array("conditions"=>$this->paginate['conditions'],'limit'=>$imageLimit,'fields'=>array("id")));
            $this->paginate['conditions']['ListingAsset.id'] = $imageIds;
        }
		$assetToShow = null;
		if($userId)
		{
			$assetToShow = $this->ListingAsset->field('id',array('ListingAsset.listing_id'=>$listingId,'ListingAsset.status'=>ListingAsset::PUBLISHED,'user_id'=>$userId),$order);
			$this->set("assetToShow",$assetToShow);
		}
		$listingData = $this->ListingAsset->Listing->find('first',array('conditions'=>array('Listing.id'=>$listingId),'recursive'=>-1));
		$this->pageTitle = sprintf(__('%s\'s Gallery'),$listingData['Listing']['title']);
		$this->set("listing",$listingData);
		$this->set("listingGallery",true);
	}
	
	function __userGallery()
	{
		if(!isset($this->params['named']['user']))
		{
			$this->__invalidUrl('Invalid parameter.');
		}
		
		$userSlug = $this->params['named']['user'];
		$user = $this->ListingAsset->User->find('first',array('conditions'=>array('User.slug'=>$userSlug),'recursive'=>-1));
		$this->set('user',$user);
		if(empty($user))
		{
			$this->__invalidUrl();
		}
					
		$this->ListingAsset->setScope('published');	
		$this->paginate['conditions'][] = array('ListingAsset.user_id' => $user['User']['id']);
		$this->pageTitle = sprintf(__('%s \'s Gallery'),$user['User']['display_name']);
		$this->set("userGallery",true);
	}
	
	function __myGallery()
	{
		$authedUser = $this->Session->read('Auth.User');
		if(empty($authedUser))
		{
			$this->__invalidUrl(null,$this->referer());
		}
		$this->pageTitle = __('My Gallery');
		$this->ListingAsset->setScope('published');		
		$this->paginate['conditions'] = array('ListingAsset.user_id'=>$authedUser['id']);
	}
	
	function admin_index($listingId = null)
	{			
		$this->helpers[] = 'assets.Gallery';
		$listingData = $this->ListingAsset->Listing->find('first',array('conditions'=>array('Listing.id'=>$listingId),'recursive'=>-1));
		if(empty($listingData))
		{
			$this->__invalidUrl('Invalid parameter.');
		}
		$this->paginate['recursive'] = -1;
		$this->paginate['conditions'] = array('ListingAsset.listing_id'=>$listingData['Listing']['id']);
				
		$this->set('listing',$listingData);
		$this->pageTitle = sprintf(__('%s\'s Gallery'),$listingData['Listing']['title']);
		$listingAssets = $this->paginate();
		$this->set(compact('listingAssets'));
	}
	
		
	function __invalidUrl($msg = null, $url = null)
	{
		if(empty($msg))
		{
			$msg = __("Invalid URL");
		}
		if(empty($url))
		{
			$url = "/";
		}
		$this->errorMsg($msg);
		$this->redirect($url);
	}
}
?>